package com.xdap.keymen.service.punch;

import com.definesys.mpaas.query.MpaasQuery;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.xdap.keymen.entity.*;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.motor.vo.ResponseVo;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class PunchMallOrderService extends PunchBaseService{

    private final SnowflakeIdWorker snowflakeIdWorker;
    private final PunchEmployeeService punchEmployeeService;

    public ResponseVo getMallOrderList(String rv) {
        //为空则到表中取
        if (StringUtils.isEmpty(rv)) {
            rv=getMaxRvid("punch_mall_order").toString();
        }
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        //每页条数
        int sz=20;
        //页面
        int pg=1;
        //记录总数
        //int maxCount=this.countEmployees(rv);
        int maxCount=20;
        //log.info("最大记录数maxCount:{}",maxCount);
        // 计算总页数 (向上取整)
        int totalPages = (int) Math.ceil((double) maxCount / sz);
        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
            headers=new HashMap<>();
            headers.put("Authorization", "Bearer "+getPunchToken());
            String response = okHttpUtils.doGet(getPunchUrl().concat("/CRM/api/MALLCO/"+rv+"/"+sz+"/"+currentPage), params,headers);
            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
            List<PunchMallOrderResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchMallOrderResponseEntity>>(){}.getType());
            for(PunchMallOrderResponseEntity punchMallOrderResponseEntity:list){
                saveOrUpdateMallOrder(punchMallOrderResponseEntity);
            }

            // 如果已经是最后一页，退出循环
            if (currentPage == totalPages) {
                break;
            }
        }

        return ResponseVo.ok().setData(maxCount);
    }

    private void saveOrUpdateMallOrder(PunchMallOrderResponseEntity entity) {

        PunchEmployeeEntity inSales = punchEmployeeService.getUserByGonghao(removeSpaces(entity.getIn_saler()));
        String strInSales=removeSpaces(entity.getIn_saler());
        String strInSalesName="";
        if(inSales!=null){
            strInSalesName=inSales.getUsername();
        }

        PunchEmployeeEntity slsman = punchEmployeeService.getUserByGonghao(removeSpaces(entity.getSlsman()));
        String strSlsman=removeSpaces(entity.getSlsman());
        String strSlsmanName="";
        if(slsman!=null){
            strSlsmanName=slsman.getUsername();
        }

        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select id from punch_mall_order where ref_number='"+removeSpaces(entity.getConum())+"'");
        String id= query.doQueryFirst(String.class);
        if (id!=null) {
            //更新
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.update("client_number",removeSpaces(entity.getCustnum()));
            query.update("contact_name",removeSpaces(entity.getContact()));
            query.update("contact_information",removeSpaces(entity.getContactTel()));
            query.update("order_date",removeSpaces(entity.getOrder_date()));
            query.update("remarks",removeSpaces(entity.getMemo()));
            query.update("client_name",removeSpaces(entity.getName()));
            query.update("salesperson",strSlsman);
            query.update("slsman_name",strSlsmanName);
            query.update("sales_back_office",strInSales);
            query.update("in_saler_name",strInSalesName);
            query.update("tax_code",removeSpaces(entity.getTax_code()));
            query.update("curr_code",removeSpaces(entity.getCurr_code()));
            query.update("area",removeSpaces(entity.getArea()));
            query.update("rvid",entity.getRvid());
            query.update("last_update_date",new Date());
            query.eq("ref_number", removeSpaces(entity.getConum()));
            query.doUpdate(PunchMallOrderEntity.class);
        }else{
            //新增
            PunchMallOrderEntity punchMallOrderEntity = new PunchMallOrderEntity();
            punchMallOrderEntity.setId(snowflakeIdWorker.nextId());
            punchMallOrderEntity.setDocumentId(snowflakeIdWorker.nextId());
            punchMallOrderEntity.setRvid(entity.getRvid());
            punchMallOrderEntity.setConum(removeSpaces(entity.getConum()));
            punchMallOrderEntity.setCustnum(removeSpaces(entity.getCustnum()));
            punchMallOrderEntity.setContact(removeSpaces(entity.getContact()));
            punchMallOrderEntity.setContactTel(removeSpaces(entity.getContactTel()));
            punchMallOrderEntity.setOrderDate(removeSpaces(entity.getOrder_date()));
            punchMallOrderEntity.setMemo(removeSpaces(entity.getMemo()));
            punchMallOrderEntity.setName(removeSpaces(entity.getName()));
            punchMallOrderEntity.setSlsman(strSlsman);
            punchMallOrderEntity.setSlsmanName(strSlsmanName);
            punchMallOrderEntity.setInSaler(strInSales);
            punchMallOrderEntity.setInSalerName(strInSalesName);
            punchMallOrderEntity.setTaxCode(entity.getTax_code());
            punchMallOrderEntity.setCurrCode(entity.getCurr_code());
            punchMallOrderEntity.setArea(entity.getArea());
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.doInsert(punchMallOrderEntity);

        }

    }

    public ResponseVo getMallOrderItemList(String rv) {
        //为空则到表中取
        if (StringUtils.isEmpty(rv)) {
            rv=getMaxRvid("punch_mall_order_details").toString();
        }
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        //每页条数
        int sz=50;
        //页面
        int pg=1;
        //记录总数
        //int maxCount=this.countEmployees(rv);
        int maxCount=800;
        log.info("最大记录数maxCount:{}",maxCount);
        // 计算总页数 (向上取整)
        int totalPages = (int) Math.ceil((double) maxCount / sz);
        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
            headers=new HashMap<>();
            headers.put("Authorization", "Bearer "+getPunchToken());
            String response = okHttpUtils.doGet(getPunchUrl().concat("/CRM/api/MALLCOItem/"+rv+"/"+sz+"/"+currentPage), params,headers);
            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
            List<PunchMallOrderItemResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchMallOrderItemResponseEntity>>(){}.getType());
            for(PunchMallOrderItemResponseEntity itemResponseEntity:list){
                saveOrUpdateMallOrderItem(itemResponseEntity);
            }

            // 如果已经是最后一页，退出循环
            if (currentPage == totalPages) {
                break;
            }
        }

        return ResponseVo.ok().setData(maxCount);
    }

    private void saveOrUpdateMallOrderItem(PunchMallOrderItemResponseEntity entity) {
        PunchMallOrderEntity punchMallOrderEntity = getMallOrder(StringUtils.strip(entity.getCONum()));
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select id from punch_mall_order_details where CONum='"+removeSpaces(entity.getCONum())+"' and ref_line="+entity.getCoLine());
        String id= query.doQueryFirst(String.class);
        if (id!=null) {
            //更新
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.update("quantity",entity.getQtyOrder());
            query.update("product_model",StringUtils.strip(entity.getDescription()));
            if(punchMallOrderEntity!=null){
                query.update("tab_doc_id",punchMallOrderEntity.getDocumentId());
            }
            query.update("expected_shipping_date",entity.getDueDate());
            query.update("estimated_arrival_days",entity.getDelivery());
            query.update("product_model",removeSpaces(entity.getCustItemDesc()));
            query.update("material_description",removeSpaces(entity.getDescription()));
            query.update("material_code",removeSpaces(entity.getMaterialCode()));

            query.update("last_update_date",new Date());
            query.eq("CONum", StringUtils.strip(entity.getCONum()));
            query.eq("ref_line", String.valueOf(entity.getCoLine()));

            query.doUpdate(PunchMallOrderItemEntity.class);
        }else{

            //新增
            PunchMallOrderItemEntity orderItemEntity = new PunchMallOrderItemEntity();
            orderItemEntity.setId(snowflakeIdWorker.nextId());
            orderItemEntity.setDocumentId(snowflakeIdWorker.nextId());
            orderItemEntity.setRvid(entity.getRvid());
            orderItemEntity.setCONum(StringUtils.strip(entity.getCONum()));
            orderItemEntity.setQuantity(entity.getQtyOrder());
            orderItemEntity.setExpectedShippingDate(entity.getDueDate());
            orderItemEntity.setEstimatedArrivalDays(entity.getDelivery());
            orderItemEntity.setRefLine(entity.getCoLine());
            orderItemEntity.setProductModel(removeSpaces(entity.getCustItemDesc()));
            orderItemEntity.setCONum(removeSpaces(entity.getCONum()));
            orderItemEntity.setMaterialDescription(removeSpaces(entity.getDescription()));
            orderItemEntity.setMaterialCode(removeSpaces(entity.getMaterialCode()));
            if(punchMallOrderEntity!=null){
                orderItemEntity.setTabDocId(punchMallOrderEntity.getDocumentId());
            }
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.doInsert(orderItemEntity);

        }

    }

    private PunchMallOrderEntity getMallOrder(String refNumber) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select * from punch_mall_order where ref_number='"+refNumber+"'");
        return query.doQueryFirst(PunchMallOrderEntity.class);
    }
}
